const express = require('express');
const multer = require('multer');
const path = require('path');
const { authenticateToken } = require('../middleware/auth');
const cloudStorageService = require('../services/cloudStorage');

const router = express.Router();

// 配置multer用于文件上传
const storage = multer.memoryStorage();
const upload = multer({
  storage: storage,
  limits: {
    fileSize: 100 * 1024 * 1024, // 100MB
    files: 10 // 最多10个文件
  },
  fileFilter: (req, file, cb) => {
    // 处理文件名编码问题
    let originalName = file.originalname;
    console.log('文件上传检查 - 原始文件名:', originalName);
    
    // 如果文件名是Buffer，尝试解码
    if (Buffer.isBuffer(originalName)) {
      originalName = originalName.toString('utf8');
      console.log('Buffer解码后:', originalName);
    }
    
    // 先提取扩展名，避免在处理过程中丢失
    const originalExt = path.extname(originalName).toLowerCase();
    console.log('原始扩展名:', originalExt);
    
    // 如果文件名包含乱码字符，尝试修复
    if (originalName.includes('\\x') || /[\x00-\x1F\x7F-\x9F]/.test(originalName) || /[^\x00-\x7F]/.test(originalName)) {
      try {
        // 尝试从Content-Disposition头解析文件名
        const matches = originalName.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
        if (matches && matches[1]) {
          const newName = matches[1].replace(/['"]/g, '');
          // 尝试解码URL编码的文件名
          try {
            originalName = decodeURIComponent(newName);
          } catch (e) {
            originalName = newName;
          }
          console.log('Content-Disposition解析后:', originalName);
        } else {
          // 如果没有Content-Disposition，尝试直接解码
          try {
            // 尝试UTF-8解码
            const buffer = Buffer.from(originalName, 'latin1');
            const decoded = buffer.toString('utf8');
            if (decoded !== originalName) {
              originalName = decoded;
              console.log('UTF-8解码后:', originalName);
            }
          } catch (e) {
            console.warn('UTF-8解码失败，使用原始名称');
          }
        }
      } catch (e) {
        console.warn('无法解析文件名，使用原始名称');
      }
    }
    
    // 清理文件名，移除特殊字符但保留中文
    originalName = originalName.replace(/[<>:"/\\|?*]/g, '_');
    
    // 确保文件名不为空
    if (!originalName || originalName.trim() === '') {
      originalName = 'unnamed_file';
    }
    
    // 确保扩展名存在，如果丢失则添加原始扩展名
    const finalExt = path.extname(originalName).toLowerCase();
    if (!finalExt && originalExt) {
      originalName = originalName + originalExt;
      console.log('恢复扩展名后:', originalName);
    }
    
    // 更新file对象的originalname
    file.originalname = originalName;
    
    // 检查文件类型
    const ext = path.extname(originalName).toLowerCase();
    console.log('文件上传检查 - 处理后文件名:', originalName);
    console.log('文件上传检查 - 最终扩展名:', ext);
    
    const allowedTypes = [
      '.pdf', '.doc', '.docx', '.txt', '.md', '.rtf',
      '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg',
      '.mp3', '.wav', '.flac', '.aac', '.ogg',
      '.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm',
      '.zip', '.rar', '.7z', '.tar', '.gz',
      '.js', '.ts', '.jsx', '.tsx', '.html', '.css', '.scss', '.less',
      '.py', '.java', '.cpp', '.c', '.h', '.php', '.rb', '.go',
      '.json', '.xml', '.yaml', '.yml', '.sql', '.sh', '.bat'
    ];
    
    if (allowedTypes.includes(ext)) {
      console.log('文件类型检查通过:', ext);
      cb(null, true);
    } else {
      console.log('文件类型检查失败:', ext, '不在允许列表中');
      cb(new Error(`不支持的文件类型: ${ext}`), false);
    }
  }
});

// 初始化云盘存储
router.get('/init', authenticateToken, async (req, res) => {
  try {
    await cloudStorageService.initializeStorage();
    res.json({ success: true, message: '云盘存储初始化成功' });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 获取存储统计信息
router.get('/stats', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const stats = await cloudStorageService.getStorageStats(userId);
    res.json(stats);
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 创建文件夹
router.post('/folders', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { folderName, parentId } = req.body;
    
    if (!folderName) {
      return res.status(400).json({ success: false, message: '文件夹名称不能为空' });
    }

    const result = await cloudStorageService.createFolder(userId, folderName, parentId);
    res.json(result);
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 获取文件夹列表
router.get('/folders', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { parentId } = req.query;
    
    // 处理parentId参数，空字符串转换为null
    const folderId = parentId && parentId !== '' ? parseInt(parentId) : null;
    
    const result = await cloudStorageService.getUserFolders(userId, folderId);
    res.json(result);
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 重命名文件夹
router.put('/folders/:folderId', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { folderId } = req.params;
    const { folderName } = req.body;
    
    if (!folderName) {
      return res.status(400).json({ success: false, message: '文件夹名称不能为空' });
    }

    const result = await cloudStorageService.renameFolder(userId, parseInt(folderId), folderName);
    res.json(result);
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 删除文件夹
router.delete('/folders/:folderId', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { folderId } = req.params;
    
    const result = await cloudStorageService.deleteFolder(userId, parseInt(folderId));
    res.json(result);
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 上传文件
router.post('/upload', authenticateToken, upload.array('files', 10), async (req, res) => {
  try {
    const userId = req.user.id;
    const { folderId } = req.body;
    const files = req.files;

    if (!files || files.length === 0) {
      return res.status(400).json({ success: false, message: '没有选择文件' });
    }

    const results = [];
    let successCount = 0;
    let skipCount = 0;
    let errorCount = 0;

    for (const file of files) {
      const result = await cloudStorageService.uploadFile(userId, file, folderId);
      results.push(result);
      
      if (result.success) {
        successCount++;
      } else if (result.error === '文件已存在') {
        skipCount++;
      } else {
        errorCount++;
      }
    }

    let message = '文件上传完成';
    if (skipCount > 0) {
      message += `，跳过 ${skipCount} 个重复文件`;
    }
    if (errorCount > 0) {
      message += `，${errorCount} 个文件上传失败`;
    }

    res.json({
      success: true,
      message,
      results,
      stats: {
        total: files.length,
        success: successCount,
        skipped: skipCount,
        errors: errorCount
      }
    });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 获取文件列表
router.get('/files', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { folderId, page = 1, limit = 20 } = req.query;
    
    // 处理folderId参数，空字符串转换为null
    const targetFolderId = folderId && folderId !== '' ? parseInt(folderId) : null;
    
    const result = await cloudStorageService.getUserFiles(
      userId, 
      targetFolderId, 
      parseInt(page), 
      parseInt(limit)
    );
    res.json(result);
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 下载文件
router.get('/download/:fileId', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { fileId } = req.params;
    
    const { query } = require('../config/database');
    const file = await query(
      'SELECT * FROM cloud_files WHERE id = ? AND user_id = ?',
      [fileId, userId]
    );

    if (file.length === 0) {
      return res.status(404).json({ success: false, message: '文件不存在' });
    }

    const fileInfo = file[0];
    
    // 更新下载次数
    await query(
      'UPDATE cloud_files SET download_count = download_count + 1 WHERE id = ?',
      [fileId]
    );

    // 记录下载日志
    await cloudStorageService.logFileOperation(userId, fileId, 'download', {
      fileName: fileInfo.file_name
    });

    res.download(fileInfo.file_path, fileInfo.file_name);
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 删除文件
router.delete('/files/:fileId', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { fileId } = req.params;
    
    const result = await cloudStorageService.deleteFile(userId, fileId);
    res.json(result);
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 重命名文件
router.put('/files/:fileId/rename', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { fileId } = req.params;
    const { newName } = req.body;
    
    if (!newName) {
      return res.status(400).json({ success: false, message: '新文件名不能为空' });
    }

    const result = await cloudStorageService.renameFile(userId, fileId, newName);
    res.json(result);
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 移动文件
router.put('/files/:fileId/move', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { fileId } = req.params;
    const { newFolderId } = req.body;
    
    const result = await cloudStorageService.moveFile(userId, fileId, newFolderId);
    res.json(result);
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 创建文件分享链接
router.post('/files/:fileId/share', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { fileId } = req.params;
    const { shareType = 'private', password = null, expiresAt = null } = req.body;
    
    const result = await cloudStorageService.createFileShare(
      userId, 
      fileId, 
      shareType, 
      password, 
      expiresAt
    );
    res.json(result);
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 获取分享文件信息（用于前端页面）
router.get('/share/:shareToken/info', async (req, res) => {
  try {
    const { shareToken } = req.params;
    const { query } = require('../config/database');
    
    const share = await query(
      `SELECT fs.*, cf.file_name, cf.file_size, cf.mime_type, cf.file_path
       FROM file_shares fs
       JOIN cloud_files cf ON fs.file_id = cf.id
       WHERE fs.share_token = ? AND fs.is_active = TRUE 
       AND (fs.expires_at IS NULL OR fs.expires_at > NOW())`,
      [shareToken]
    );

    if (share.length === 0) {
      return res.status(404).json({ success: false, message: '分享链接不存在或已过期' });
    }

    const shareInfo = share[0];
    
    // 返回分享信息（不重定向）
    return res.json({
      success: true,
      requiresPassword: !!shareInfo.share_password,
      fileName: shareInfo.file_name,
      fileSize: shareInfo.file_size
    });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 获取分享文件信息（用于直接访问）
router.get('/share/:shareToken', async (req, res) => {
  try {
    const { shareToken } = req.params;
    const { query } = require('../config/database');
    
    const share = await query(
      `SELECT fs.*, cf.file_name, cf.file_size, cf.mime_type, cf.file_path
       FROM file_shares fs
       JOIN cloud_files cf ON fs.file_id = cf.id
       WHERE fs.share_token = ? AND fs.is_active = TRUE 
       AND (fs.expires_at IS NULL OR fs.expires_at > NOW())`,
      [shareToken]
    );

    if (share.length === 0) {
      return res.status(404).json({ success: false, message: '分享链接不存在或已过期' });
    }

    const shareInfo = share[0];
    
    // 检查是否需要密码（根据share_password字段判断）
    if (shareInfo.share_password) {
      return res.json({
        success: true,
        requiresPassword: true,
        fileName: shareInfo.file_name,
        fileSize: shareInfo.file_size
      });
    }

    // 重定向到前端分享页面
    const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:3000';
    return res.redirect(`${frontendUrl}/share/${shareToken}`);
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 下载分享文件
router.get('/share/:shareToken/download', async (req, res) => {
  try {
    const { shareToken } = req.params;
    const { query } = require('../config/database');
    
    const share = await query(
      `SELECT fs.*, cf.file_name, cf.file_size, cf.mime_type, cf.file_path
       FROM file_shares fs
       JOIN cloud_files cf ON fs.file_id = cf.id
       WHERE fs.share_token = ? AND fs.is_active = TRUE 
       AND (fs.expires_at IS NULL OR fs.expires_at > NOW())`,
      [shareToken]
    );

    if (share.length === 0) {
      return res.status(404).json({ success: false, message: '分享链接不存在或已过期' });
    }

    const shareInfo = share[0];
    
    // 检查是否需要密码
    if (shareInfo.share_password) {
      return res.status(401).json({ success: false, message: '需要密码验证' });
    }

    // 更新下载次数
    await query(
      'UPDATE file_shares SET download_count = download_count + 1 WHERE id = ?',
      [shareInfo.id]
    );

    res.download(shareInfo.file_path, shareInfo.file_name);
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 验证分享密码
router.post('/share/:shareToken/verify', async (req, res) => {
  try {
    const { shareToken } = req.params;
    const { password } = req.body;
    const { query } = require('../config/database');
    
    const share = await query(
      `SELECT fs.*, cf.file_name, cf.file_size, cf.mime_type, cf.file_path
       FROM file_shares fs
       JOIN cloud_files cf ON fs.file_id = cf.id
       WHERE fs.share_token = ? AND fs.is_active = TRUE 
       AND (fs.expires_at IS NULL OR fs.expires_at > NOW())`,
      [shareToken]
    );

    if (share.length === 0) {
      return res.status(404).json({ success: false, message: '分享链接不存在或已过期' });
    }

    const shareInfo = share[0];
    
    if (shareInfo.share_password && shareInfo.share_password !== password) {
      return res.status(401).json({ success: false, message: '密码错误' });
    }

    // 更新下载次数
    await query(
      'UPDATE file_shares SET download_count = download_count + 1 WHERE id = ?',
      [shareInfo.id]
    );

    res.download(shareInfo.file_path, shareInfo.file_name);
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 获取文件操作日志
router.get('/logs', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { page = 1, limit = 20 } = req.query;
    const offset = (page - 1) * limit;
    
    const { query } = require('../config/database');
    const logs = await query(
      `SELECT fo.*, cf.file_name
       FROM file_operations fo
       LEFT JOIN cloud_files cf ON fo.file_id = cf.id
       WHERE fo.user_id = ?
       ORDER BY fo.created_at DESC
       LIMIT ? OFFSET ?`,
      [userId, parseInt(limit), offset]
    );

    const total = await query(
      'SELECT COUNT(*) as count FROM file_operations WHERE user_id = ?',
      [userId]
    );

    res.json({
      success: true,
      logs,
      total: total[0].count,
      page: parseInt(page),
      limit: parseInt(limit)
    });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

module.exports = router;
